#include "customlistwidget.h"
#include <QDebug>
#include <QDropEvent>
#include <QUrl>
#include <QFileInfo>
#include <mainwindow.h>


customListWidget::customListWidget(QWidget *parent)
    : QListWidget(parent)
{
    setDragDropMode(QAbstractItemView::DragDrop);
    setDefaultDropAction(Qt::MoveAction);
}

bool isJPG(QFileInfo file){
    QString name = file.fileName().toLower();
    if(name.endsWith(".jpg")){
        return true;
    }
    else{
        return false;
    }
}

bool customListWidget::dropMimeData(int index, const QMimeData *data, Qt::DropAction action)
{
    QList <QUrl> urlList;
    QListWidgetItem *item;
    QFileInfo info;
    QString fName;

    urlList = data->urls(); // retrieve list of urls

    foreach(QUrl url, urlList) // iterate over list
    {
        fName = url.toLocalFile();
        info.setFile( fName );
        if(isJPG(info)){
            QList<QListWidgetItem*> items = findItems(QString("*"), Qt::MatchWrap | Qt::MatchWildcard);
            bool unique=true;
            for(int i=0;i<items.size();i++){
                if(items.at(i)->text()==info.filePath()){
                    unique = false;
                }
            }
            if(unique){
                item = new QListWidgetItem(info.filePath());
                insertItem(index, item);
                emit newItemAdded(item);
                ++index; // increment index to preserve drop order
            }
        }
    }

    return true;
}


QStringList customListWidget::mimeTypes () const
{
    QStringList qstrList;
    // list of accepted mime types for drop
    qstrList.append("text/uri-list");
    return qstrList;
}


Qt::DropActions customListWidget::supportedDropActions () const
{
    // returns what actions are supported when dropping
    return Qt::CopyAction | Qt::MoveAction;
}

